const express = require('express');
const router = express.Router();
const { success, failure } = require('../utils/responses');
const { singleFileUpload, uploadToBOS } = require('../utils/baiduyun');
const { Attachment } = require('../models');
//const { v4: uuidv4 } = require('uuid');
//const moment = require('moment');


/**
 * 百度云 BOS 客户端上传
 * POST /uploads/baiduyun
 */
router.post('/baiduyun', function (req, res) {
  try {
    singleFileUpload(req, res, async function (error) {
      if (error) {
        return failure(res, error);
      }

      if (!req.file) {
        return failure(res, new BadRequest('请选择要上传的文件。'));
      }
      req.file.url = await uploadToBOS(req.file.buffer, req.file.originalname);
      //记录附件信息
      await Attachment.create({
        ...req.file,
        // 有部分同学碰到上传中文文件名，数据库中出现乱码问题。
        // 可取消以下这行的屏蔽后，再尝试一下。
        // originalname: Buffer.from(req.file.originalname, 'latin1').toString()
        userId: req.userId,
        fullpath: req.file.url,
        filename: req.file.fieldname,
      })
      success(res, '上传成功。', { file: req.file.url });
    });
  } catch (error) {
    failure(res, error);
  }
})

module.exports = router;